package com.hslxy.niukewang.controller;

import com.hslxy.niukewang.service.AlphaDaoService;
import com.hslxy.niukewang.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    @Autowired
    AlphaDaoService alphaDaoService;

    private static final Logger logger = LoggerFactory.getLogger(AlphaController.class);

    @RequestMapping("/hello")
    @ResponseBody
    public String helloworld(){
        return "hello";
    }
    @RequestMapping("/find")
    @ResponseBody
    public String find(){
        return alphaDaoService.find();
    }

    @RequestMapping("/http")
//    这里用的void，原因就是可以通过response得到返回值
    public void http(HttpServletRequest request, HttpServletResponse response){
//        请求
//        得到请求第一行的内容
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
//        得到请求头的东西
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.out.println(s +": "+header);
        }
//        得到参数
        System.out.println(request.getParameter("code"));

//        返回响应结果
        response.setContentType("text/html;charset=utf-8");
        try (
            PrintWriter writer = response.getWriter()
                ){
            writer.write("<h1>lxy</h1>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

//    /students?current=1&limit=12
    @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit){
        System.out.println(current + " " + limit);
        return "some students";
    }

//    /student/123
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id){
        System.out.println(id);
        return "a student";
    }

//  post
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String postStudent(String name, int age){
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
//    没这个注解默认返回html
//    @ResponseBody
    public ModelAndView getTeacher(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", "zha");
        modelAndView.addObject("age", 30);
        modelAndView.setViewName("/demo/view");
        return modelAndView;
    }

    @RequestMapping(path = "/school", method = RequestMethod.GET)
//    没这个注解默认返回html
//    @ResponseBody
    public String getSchool(Model model){
        model.addAttribute("name", "zha");
        model.addAttribute("age", "1");
        return "/demo/view";
    }

//    响应JSON数据
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp(){
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "zhass");
        emp.put("age", 23);
        emp.put("aaa", 222);
        return emp;
    }

    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps(){
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "zhass");
        emp.put("age", 23);
        emp.put("aaa", 222);
        list.add(emp);
        return list;
    }

//    cookie示例
    @RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response){
//        创建一个cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
//        设置生效范围
        cookie.setPath("/niukewang/alpha");
//        设置生存时间
        cookie.setMaxAge(60 * 10);
//        设置cookie
        response.addCookie(cookie);

        return "set cookie";
    }

    @RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){
        System.out.println(code);
        return "get cookie";
    }

//    session示例
    @RequestMapping(path = "/session/set", method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("id", 1);
        session.setAttribute("name", "t");
        return "set session";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session){
        Object id = session.getAttribute("id");
        Object name = session.getAttribute("name");
        System.out.println(id);
        System.out.println(name);
        return "get session";
    }

    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String postAjax(String name, int age){
        System.out.println(name);
        System.out.println(age);
        String aa = CommunityUtil.getJSONString(404, "aa");
        return aa;
    }

//    可以在多线程环境下异步调用
    @Async
    public void execute(){
        logger.debug("execute");
    }

//    @Scheduled(initialDelay = 10000, fixedRate = 1000)
//    public void execute2(){
//        logger.debug("execute");
//    }
}
